<template>
  <div class="comment-list">
    <van-list
      v-model="loading"
      :finished="finished"
      :error="error"
      error-text="加载失败"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <CommentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
      />
    </van-list>
  </div>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList',
  components: {
    CommentItem
  },
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    idType: {
      type: String,
      required: true
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      loading: false,
      finished: false,
      offset: null, // 下一次请求的评论的标记（上次请求最后一个评论的id
      limit: 10, // 一页请求几条数据
      error: false
    }
  },
  created () {
    this.loading = true
    this.onLoad()
  },
  methods: {
    async onLoad () {
      try {
        // 获取文章评论和评论回复的接口一样。只不过参数不同
        // type：文章为a，评论回复为c
        // source为文章id或评论id
        const { data } = await getComments({
          type: this.idType,
          source: this.source.toString(),
          offset: this.offset,
          limit: this.limit
        })
        const { results } = data.data
        this.list.push(...results)
        // 把评论数据传到父组件中
        this.$emit('loadCommentSuccess', data)
        this.loading = false
        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less">

</style>
